//
//  XHEditRecipeTableViewCell.m
//  meiang_edu
//
//  Created by 徐辉 on 2019/1/17.
//  Copyright © 2019年 com.meiang.meiang_edu. All rights reserved.
//

#import "XHEditRecipeTableViewCell.h"
#import "XHEditRecipeCollectionViewCell.h"
#import "UIView+ShowView.h"
#import "XHRecipeModel.h"

@interface XHEditRecipeTableViewCell()<UIActionSheetDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UILabel * titleLabel;
@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic,strong) NSMutableArray * collectionArray;
@property (nonatomic,strong) NSIndexPath * indexPath;
@property (nonatomic,strong) UIView * backView;
@property (nonatomic,copy) NSString * photoAlbum_id;//相册id

@end

@implementation XHEditRecipeTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.collectionArray = [NSMutableArray array];
        self.photoAlbum_id = @"474700ad-5c31-4df7-ab74-fe7b392cec41";
        self.contentView.backgroundColor = FFColor(0xebebeb);
        [self addSubViews];
    }
    return self;
}

- (void)addSubViews
{
    self.backView = [[UIView alloc] init];
    self.backView.backgroundColor = [UIColor whiteColor];
    self.backView.layer.masksToBounds = YES;
    self.backView.layer.cornerRadius = 7 * kScale;
    [self.contentView addSubview:self.backView];
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.contentView.mas_left);
         make.top.equalTo(self.contentView.mas_top);
         make.right.equalTo(self.contentView.mas_right);
         make.bottom.equalTo(self.contentView.mas_bottom);
     }];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.textAlignment = NSTextAlignmentLeft;
    self.titleLabel.font = [UIFont fontWithName:kMainFontFormat size:14 * kScale];
    self.titleLabel.textColor = FFColor(0xff9000);
    [self.contentView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.contentView.mas_left).offset(12 * kScale);
         make.top.equalTo(self.contentView.mas_top).offset(12 * kScale);
     }];
    
    UICollectionViewFlowLayout  *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
//    layout.minimumLineSpacing = 2 * kScale;
//    layout.minimumInteritemSpacing = 12 * kScale;
//    layout.estimatedItemSize = CGSizeMake(108 * kScale, 88 * kScale);
//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
//
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.contentView.bounds collectionViewLayout:layout];
    [self.collectionView registerClass:[XHEditRecipeCollectionViewCell class] forCellWithReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([XHEditRecipeCollectionViewCell class])]];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.contentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.contentView.mas_left);
         make.top.equalTo(self.titleLabel.mas_bottom).offset(12 * kScale);
         make.right.equalTo(self.contentView.mas_right).offset(-12 * kScale);
         make.bottom.equalTo(self.contentView.mas_bottom).offset(-12 * kScale);
     }];
  
}




-(void)deleteCard{
    //    WGQGrowUpLittleModel * model = self.collectionArray[self.indexPath.row];
    XHRecipeModel *modelData = self.collectionArray[self.indexPath.row];
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         XHRecipeModel * model = modelData;
         request.URLString = [NSString stringWithFormat:@"http://www.armyant.com.cn:8082/Army/v1.1_photo/delete_id?ids=%@",model.ps_id];
         request.methodType = ZBMethodTypePOST;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             if (self.image_save_success_block)
             {
                 self.image_save_success_block(@"图片已删除");
             }
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}


- (void)saveImageBtnActionWithImage:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (self.image_save_success_block)
    {
        self.image_save_success_block(@"图片已保存至本地");
    }
}

//图片另存至相册,发生网络请求，将图片存在当前账户下的某个相册
- (void)photoSaveToAlbumsWithImageUrl:(NSString *)string
{
    //    WGQGrowUpLittleModel * model = self.collectionArray[self.indexPath.row];
    XHRecipeModel *modelData = self.collectionArray[self.indexPath.row];
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         
         XHRecipeModel * model = modelData;
         request.URLString = [NSString stringWithFormat:@"%@?ids=%@&ph_id=%@",Photo_copy,model.ps_id,self.photoAlbum_id];
         
         request.methodType = ZBMethodTypePOST;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             if (self.image_save_success_block)
             {
                 self.image_save_success_block(@"图片已保存至相册");
             }
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.collectionArray count]+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   XHEditRecipeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([XHEditRecipeCollectionViewCell class])] forIndexPath:indexPath];
    cell.closeButton.tag = indexPath.row;
    if (indexPath.row == self.collectionArray.count) {
        cell.closeButton.hidden = YES;
        cell.descLabel.text = @"";
        [cell.imageView setImage:[UIImage imageNamed:@"addimage_logo"]];
        
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPhotoImage:)];
        cell.imageView.userInteractionEnabled = YES;
        [cell.imageView addGestureRecognizer:tapGesture];
    } else {
        cell.closeButton.hidden = NO;
        cell.imageView.userInteractionEnabled = NO;
        [cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
        [cell setObject:self.collectionArray[indexPath.row]];
    }
   
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(102 * kScale, 88 * kScale);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(0, 0);
}

- (void)setObject:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary * dict = object;
        self.titleLabel.text = dict[@"title"];
        NSArray * array = dict[@"array"];
        
        if (self.collectionArray.count == 0){
            self.collectionArray = [NSMutableArray arrayWithArray:array];
        }
        
        
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make)
         {
             make.left.equalTo(self.contentView.mas_left).offset(12 * kScale);
             make.right.equalTo(self.contentView.mas_right).offset(-12 * kScale);
             if (self.collectionArray.count <= 0)
             {
                 self.backView.backgroundColor = FFColor(0xebebeb);
                 make.top.equalTo(self.contentView.mas_top);
                 make.height.priorityHigh().equalTo(@(0));
                 make.bottom.equalTo(self.contentView.mas_bottom).offset(-1);
             }
             else
             {
                 self.backView.backgroundColor = [UIColor whiteColor];
                 make.top.equalTo(self.titleLabel.mas_bottom).offset(12 * kScale);
                 make.height.priorityHigh().equalTo(@(ceil((self.collectionArray.count+1) / 3.0) * 90 * kScale + 12 * kScale * floorf((self.collectionArray.count) / 3)));
                 make.bottom.equalTo(self.contentView.mas_bottom).offset(-12 * kScale);
             }
         }];
        [self.collectionView reloadData];
    }
}

- (void)deletePhoto:(UIButton *)sender{
    
    
    //    WGQGrowUpLittleModel * model = self.collectionArray[self.indexPath.row];
    XHRecipeModel *modelData = self.collectionArray[sender.tag];

    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         XHRecipeModel * model = modelData;
         request.URLString = [NSString stringWithFormat:@"http://www.armyant.com.cn:8082/Army/v1.1_menu/delete_%@?ids=%@",model.or_id,model._id];
         request.methodType = ZBMethodTypePOST;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             self.image_save_success_block(@"图片已删除");
             
             [self.collectionArray removeObjectAtIndex:sender.tag];
             
             
             if ((self.collectionArray.count+1)%3 != 0){
                 
                 self.collectionView.height = ((self.collectionArray.count+1)/3+1)*102*kScale;
                 
             }else{
                 self.collectionView.height = (self.collectionArray.count+1)/3*102*kScale;
             }
             [self.contentView addSubview:self.collectionView];
             [self.collectionView reloadData];
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);

     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];

}

- (void)tapPhotoImage:(UITapGestureRecognizer *)tap
{
    UIImageView *tapImageView = (UIImageView*)tap.view;
    NSInteger index = tapImageView.tag;
    [self endEditing:YES];
    //添加图片
    
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相机" otherButtonTitles:@"从相册选取", nil];
    
    [sheet showInView:self];
}


- (void)awakeFromNib
{
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}




@end
